import {
  listColumns,
  columns,
  shipments,
  tabArr
} from './index.const';
import {formatterPrice, formatDate} from '@const/filter'
import ElEditable from '@components/el-editable';
import { _print } from '@const/print'
import {
  orderCancel,
  orderDetailList,
  getProductLineNameList,
  checkFailMessageList,
  deleteOrder,
  statusQuantityQuery,
  getOriginalFactoryName,
  getSupplierList,
  selectOrderTypeList,
  downloadOrderList,
  orderCommonFindPrintInfo,
  downloadOrderDetailInfo,
  queryOrderPaymentVoucher,
  uploadPaymentVoucher
} from '@api/m_mall_web_v1.js';
import
tabs
from '@components/tabs/index.vue';
import {
  $loadFileSimply
} from '@const/loadFileOps.js';
import {
  fileUpload
} from '@const/api'
import { fileDownload } from '@const/utils.js';
export default {
  components: {
    ElEditable,
    tabs
  },
  inject: ['apiMMallWeb'],
  data() {
    return {
      dialogTitle: "删除订单",
      tableQuery: {
        supplierName: '',
        originalFactoryName: '',
        orderTypeId: '',
        orderCode: '',
        orderStatus: '',
        commitDateEnd: '',
        commitDateStart: '',
        productLineCode: '',
      },
      exportQuery:{
        supplierName: '',
        originalFactoryName: '',
        orderTypeId: '',
        orderCode: '',
        orderStatus: '',
        commitDateEnd: '',
        commitDateStart: '',
        productLineCode: '',
      },
      commitDate: ['', ''],
      tabArr: tabArr,
      tableLoading: false,
      tableData: {},
      columns: columns,
      shipments: shipments,
      listColumns: listColumns,
      fullscreen: false,
      dialogVisible: false,
      delDialogVisible: false,
      loading: false,
      errorMsgData: {},
      errorTableLoading: false,
      minDate: '',
      maxDate: '',
      payload: {},
      typeList: [],       //获取订单类型
      orderIds: '',
      // 产品线查询
      options: [],
      //供应商下拉
      supplierNameOptions: [],
      //生产厂家下拉
      originalFactoryNameOptions: [],
      // 主列表分页
      currentPage: 1,
      pageSize: 20,
      //检验失败列表分页
      errorCurrentPage: 1,
      errorPageSize: 20,
      detailExIsLoaded: false,
      isLoaded: false,
      showUploadDialog: false,
      imgDialogVisible: false,
      fileUploadLoading: false,
      dialogImageUrl: '',
      payPicFiles: []
    };
  },
  created() {
    this.initUploadData()
    this.getList()
    this.getOrderStatusNum()
    this.getOrdertype()
  },
  mounted() {
    let str = '';
    let arr = this.$store.state;
    arr.menuList.forEach(item => {
      item.children.forEach(val => {
        str += val.resourcePath;
      });
    });
    if (str.indexOf('financial-management/accounts-payable-managemen') === -1) {
      this.showPayBut = false;
    }
  },
  methods: {
    initUploadData () {
      this.fileUpload = fileUpload
      this.deletePayPicFiles = []
      this.selectList = []
      this.uploadPicRow = {}
      this.uploadAccept = 'image/jpg,image/png,image/jpeg'
    },
    openUploadDialog (scope) {
      this.showUploadDialog = true
      this.uploadPicRow = scope.row
      this.getOrderPayPic()
    },
    selectionChange (list) {
      this.selectList = list
    },
    uploadPayPic () {
      let next = true
      if (!this.selectList.length) {
        return this.$message.warning('请选择订单数据')
      }
      this.selectList.forEach(item => {
        if (item.orderStatus === 1 || item.orderStatus === 8 || item.orderType !== 'LCONSIGN_ISSUE') {
          next = false
        }
      })
      if (!next) {
        return this.$message.warning('请选择长期寄售销货类型，且订单状态不为待提交、已取消状态的订单')
      }
      this.showUploadDialog = true
    },
    getOrderPayPic () {
      this.fileUploadLoading = true
      this.$axios({
        url: queryOrderPaymentVoucher,
        method: 'POST',
        data: {
          orderId: this.uploadPicRow.orderId
        }
      }).then(res => {
        this.payPicFiles = res.data.payload
        this.fileUploadLoading = false
      })
    },
    closeUploadDialog () {
      this.showUploadDialog = false
      this.payPicFiles = []
      this.selectList = []
      this.uploadPicRow = {}
      this.$refs['file-upload'].clearFiles()
    },
    deleteImgItem(file, local) {
      const idKey = local ? 'uid' : 'id'
      const INDEX = this.payPicFiles.findIndex(_ => _[idKey] === file[idKey])
      !local && this.deletePayPicFiles.push(file.id)
      this.payPicFiles.splice(INDEX, 1);
    },
    beforeImgUpload(file) {
      const isImg = this.uploadAccept.includes(file.type.toLowerCase());
      const isLt5M = file.size / 1024 / 1024 <= 5;
      if (!isImg) {
        this.$message({
          message: '上传文件只支持JPG/PNG格式!',
          type: 'error',
          customClass: 'notify_class'
        })
        return false;
      }
      if (!isLt5M) {
        this.$message({
          message: '上传文件大小不能超过 5MB!',
          type: 'error',
          customClass: 'notify_class'
        })
        return false;
      }
      return true;
    },
    onChange(file, fileList) {
      this.payPicFiles = fileList
      const next = this.beforeImgUpload(file.raw)
      !next && this.deleteImgItem(file, 'local')
    },
    uploadPicConfirm () {
      // if (!this.payPicFiles.length) {
      //   return this.showUploadDialog = false
      // }
      this.fileUploadLoading = true
      let sendList = {
        index: [],
        req: []
      }
      this.payPicFiles.forEach((item, i) => {
        if (!item.id) {
          sendList.req.push(this.httpRequest(item))
          sendList.index.push(i)
        }
      })
      sendList.req.length
        ? Promise.all(sendList.req).then(resList => {
              sendList.index.forEach((index, i) => {
                resList[i].data.name = this.payPicFiles[index].name
              })
              this.savePayPic(resList)
            }).catch(err => {
              console.log(err)
              this.fileUploadLoading = false
            })
        : this.savePayPic([])
    },
    savePayPic (files) {
      let addFileList = files.map((f, i) => {
        return {
          fileUrl: f.data.payload,
          fileName: f.data.name,
          index: i + this.payPicFiles.length || 1
        }
      })
      let sendData = {
        addFileList: addFileList || [],
        delFileIdList: this.deletePayPicFiles || [],
        orderIdList: [this.uploadPicRow?.orderId || '']
      }
      if (this.selectList.length) {
        const IDS = this.selectList.map(_ => _.orderId)
        sendData = {
          addFileList: addFileList || [],
          orderIdList: IDS
        }
      }
      this.$axios({
        url: uploadPaymentVoucher,
        method: 'POST',
        data: sendData
      }).then(res => {
        this.$message.success('上传成功')
        this.getList()
      }).finally(() => {
        this.fileUploadLoading = false
        this.showUploadDialog = false
        this.payPicFiles = []
        this.deletePayPicFiles = []
        this.selectList = []
        this.uploadPicRow = {}
        this.$refs['file-upload'].clearFiles()
      })
    },
    httpRequest(data) {
      let fd = new FormData();
      fd.append('file', data.raw);
      return this.$axios({
        method: 'post',
        url: this.fileUpload,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.imgDialogVisible = true
    },
    // 打印功能添加
    async onPrint(data) {
      let printText = ''
      try {
        const printData = await this.$axios.$post(orderCommonFindPrintInfo, {orderId: data.orderId}).then(res => {
          if (res.code === '0') {
            return res.payload
          } else {
            return ''
          }
        })
        // console.log(printData, 'print')
        this.updatePrintData(printData)
        printText = this.getPrintText(printData)
      } catch (error) {
        console.log(error)
        printText = ''
      } finally {
        _print(printText, [])
      }
    },
    // 处理接口返回
    updatePrintData (data) {
      data.printInfoProduct = data.printInfoProduct || []
      let {printInfoProduct} = data
      // 总价待定
      if (data.orderAmount === '' || data.orderAmount === null || data.orderAmount === '待定') {
        data.orderAmount = '待定'
      } else {
        data.orderAmount = formatterPrice(data.orderAmount)
      }
      data.orderDate = formatDate(data.orderDate, 'YYYY-MM-DD')
      // 明细行初数据处理
      if (printInfoProduct) {
        printInfoProduct.forEach(item => {
          item.lineNum = item.lineNum + 1
          if (item.productPrice !== '待定' && item.productPrice !== '' && item.productPrice !== null) {
            item.productPrice = formatterPrice(item.productPrice)
          }
          if (item.productAmount !== '待定' && item.productAmount !== '' && item.productAmount !== null) {
            item.productAmount = formatterPrice(item.productAmount)
          }
          item.productCount = +item.productCount
        })
      }
    },
    // 获取打印内容
    getPrintText(data) {
      let columns = [
        {
          prop: 'lineNum',
          label: '行号',
          width: '60px'
        },
        {
          prop: 'model',
          label: '产品型号',
          width: '100px'
        },
        {
          prop: 'productName',
          label: '产品名称',
          width: '200px'
        },
        {
          prop: 'productCount',
          label: '数量',
          width: '60px'
        },
        {
          prop: 'productPrice',
          label: '单价',
          width: '80px'
        },
        {
          prop: 'productAmount',
          label: '总价格',
          width: '100px'
        }
      ]
      let htmlStr = `<div style="margin:0; box-sizing:border-box; height:auto font-size: 16px;">
        <div style="padding:15px 0 15px 0;">
          <h2 style="text-align:center; margin:0;">订单信息</h2>
        </div>
        <table style="border: 1px solid #000;" width="100%" border="1" cellpadding="0" cellspacing="0"  >
          <tbody>
            <tr style="height:40px;">
              <th style="border: 1px solid #000; padding: 5px; width: 60px;">
                <div style="text-align: left;">
                  订单编号：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px; width: 300px;">
                <div style="text-align: left;">
                  ${data.orderCode || ''}
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px; width: 60px;">
                <div style="text-align: left;">
                  订单状态：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px; width: 180px;">
                <div style="text-align: left;">
                ${data.orderStatusName || ''}
                </div>
              </th>
            </tr>
            <tr style="height:40px;">
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                  订单类型：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                ${data.orderTypeName || ''}
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                  供应商：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                ${data.vendorName || ''}
                </div>
              </th>
            </tr>
            <tr style="height:40px;">
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                  产品线：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                ${data.productLineName || ''}
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                  订货日期：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                ${data.orderDate}
                </div>
              </th>
            </tr>
            <tr style="height:40px;">
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                  总金额：
                </div>
              </th>
              <th style="border: 1px solid #000; padding: 5px;" colspan="3">
                <div style="text-align: left;">
                ${data.orderAmount}
                </div>
              </th>
            </tr>
          </tbody>
        </table>
        <table style="margin-top: -1px;" width="100%" border="1" cellpadding="0" cellspacing="0"  >
          ${this.getTableTheadText(columns)}
          ${this.getTableBodyText(data.printInfoProduct, columns)}
        <table>
      </div>`
      return htmlStr
    },
    getTableTheadText(columns) {
      let str = `
        <thead>
          ${columns.map(item => {
            return `
              <th style="border: 1px solid #000; padding: 5px;">
                <div style="text-align: left;">
                ${item.label}
                </div>
              </th>
            `
          }).join('')}
        </thead>
      `
      return str
    },
    getTableBodyText(list, columns) {
      let str = `
        <tbody>
          ${list.map((item,index) => {
            return `
              <tr style="height:40px;">
                ${columns.map(col => {
                  let text = item[col.prop] === undefined || item[col.prop] === null ? '' : item[col.prop]
                  return `
                    <td style="border: 1px solid #000; padding: 5px;word-break:break-all; word-wrap:break-word; width: ${col.width}">
                      <div style="text-align: left;">
                        ${text}
                      </div>
                    </td>
                  `
                }).join('')}
              </tr>
            `
          }).join('')}
        <tbody>
      `
      return str
    },
    // tableRowClassName({
    //   row,
    //   rowIndex
    // }) {
    //   if (row.orderStatus === 1) {
    //     return 'warning-row';
    //   }
    //   return '';
    // },
    //tab切换
    handletabs(index) {
      if (index === 0) {
        this.tableQuery.orderStatus = ''
      } else {
        this.tabArr.forEach((item, i) => {
          if (i === index) {
            this.tableQuery.orderStatus = item.val
          }
        })
      }
      this.queryFormQuery();
    },
    // 重置
    queryFormReset() {
      this.tableQuery = {
        supplierName: '',
        originalFactoryName: '',
        orderCode: '',
        orderTypeId: '',
        orderStatus: this.tableQuery.orderStatus,
        commitDateEnd: '',
        commitDateStart: '',
        productLineCode: ''
      }
      this.exportQuery = Object.assign({},this.tableQuery)
      this.commitDate = ['', '']
      this.currentPage = 1;
      this.getList()
    },
    // 查询
    queryFormQuery() {
      this.currentPage = 1
      this.exportQuery = Object.assign({},this.tableQuery)
      this.exportQuery.commitDateStart = this.commitDate ? this.commitDate[0] : ''
      this.exportQuery.commitDateEnd = this.commitDate ? this.commitDate[1] : ''
      this.getList()
    },
    // 产品线搜索框
    remoteMethod(val) {
      if (val !== '') {
        this.loading = true;
        let query = {
          busModel: 2,
          productLineName: val
        };
        this.$axios.$post(getProductLineNameList, query).then(res => {
          this.options = res.payload;
          this.loading = false;
        });
      }
    },
    //供应商下拉
    supplierNameRemoteMethod(val) {
      if (val !== '') {
        this.loading = true;
        let query = {
          busModel: 2,
          supplierName: val
        };
        this.$axios.$post(getSupplierList, query).then(res => {
          this.supplierNameOptions = res.payload;
          this.loading = false;

        });
      }

    },
    //生产厂家下拉
    originalFactoryNameRemoteMethod(val) {
      if (val !== '') {
        this.loading = true;
        let query = {
          busModel: 2,
          originalFactoryName: val
        };
        this.$axios.$post(getOriginalFactoryName, query).then(res => {
          this.originalFactoryNameOptions = res.payload;
          this.loading = false;

        });
      }
    },
    //获取订单类型
    getOrdertype() {
      const params = {
        busModelList:[2,4,11]
      }
      this.$axios.$post(selectOrderTypeList, params)
      .then(res => {
          this.typeList = res.payload || {}
      })
    },
    getList() {
      this.tableLoading = true;
      const query = {
        busModelList:[2,4,11],
        ...this.tableQuery,
        page: this.currentPage,
        pageSize: this.pageSize,
        commitDateStart: this.commitDate ? this.commitDate[0] : '',
        commitDateEnd: this.commitDate ? this.commitDate[1] : '',
      };
      this.$axios.$post(orderDetailList, query).then(res => {
        if (res.code === '0') {
          this.payload = res.payload;
        }
        this.tableLoading = false;
      })
    },
    getOrderStatusNum() {
      this.$axios
        .$post(statusQuantityQuery, {
          busModelList:[2,4],
          busFunctionList: [1]
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.tabArr[1].badge.value = res.payload.submitCount; // 待提交
            this.tabArr[2].badge.value = res.payload.checkCount; // 待平台审核
            // this.tabArr[3].badge.value = res.payload.payCount; // 待支付
            // this.tabArr[4].badge.value = res.payload.shipmentsCount; // 待发货
            this.tabArr[3].badge.value = res.payload.harvestCount; // 待收货
            this.tabArr[4].badge.value = res.payload. partCount; // 部分收货
            // this.tabArr[7].badge.value = res.payload.failCount; // 校验失败
          }
        });
    },
    //主列表分页器
    reloadProductData(val) {
      this.currentPage = val.number
      this.pageSize = val.size
      this.getList()
    },
    onSubmit() {},
    // 校验失败弹窗
    // showDialog(scope) {
    //   this.dialogVisible = true;
    //   this.errorListOrderId = scope.orderId
    //   this.getErrorList()
    // },
    //效验失败列表
    // getErrorList() {
    //   this.errorTableLoading = true;
    //   this.$axios
    //     .$post(checkFailMessageList, {
    //       orderId: this.errorListOrderId,
    //       page: this.errorCurrentPage,
    //       pageSize: this.errorPageSize
    //     })
    //     .then(res => {
    //       if (res.code === '0' && res.payload) {
    //         this.errorMsgData = res.payload;
    //       }
    //     });
    //   this.errorTableLoading = false;
    // },
    //检验失败分页器
    // reloadError(val) {
    //   this.errorCurrentPage = val.number
    //   this.errorPageSize = val.size
    //   this.getErrorList()
    // },
    //复制编辑
    resubmit(scope) {
      this.$router.push({
        path: '/purchase-order/consign/add',
        query: {
          id: scope.orderId,
          detailid: scope.orderDetailId
        }
      });
    },
    // /操作栏-删除及取消弹窗
    delDialog(scope) {
      this.delDialogVisible = true;
      this.orderIds = scope;
      this.dialogTitle = scope.orderStatus === 1 || scope.orderStatus === 9 ? '删除订单' : '取消订单'
    },
    // 确认删除
    delSure() {
      if (this.orderIds.orderStatus === 1 || this.orderIds.orderStatus === 9) {
        this.$axios.$post(deleteOrder, [this.orderIds.orderId]).then(res => {
          if (res.payload) {
            this.$message.success('订单删除成功');
            this.getList();
            this.getOrderStatusNum();
          } else {
            this.$message.error('订单删除失败');
          }
        });
        this.delDialogVisible = false;
      } else {
        this.$axios
          .$post(orderCancel, {
            orderCode: this.orderIds.orderCode,
            orderType: this.orderIds.orderType
          })
          .then(res => {
            if (res.payload.resultCode === 'S') {
              this.$message.success('订单取消成功');
              this.getList();
              this.getOrderStatusNum();
            } else {
              this.$message.error(res.payload.message ? res.payload.message : '订单取消失败');
            }
          });
        this.delDialogVisible = false;
      }

    },
    // 取消删除
    concelDel() {
      this.delDialogVisible = false;
    },
    //操作栏-去支付
    toPay(row) {
      this.$router.push({
        path: '/financial-management/accounts-payable-managemen/list',
        query: {
          orderId: row.orderId,
        }
      });
    },
    //收货
    takeDialog(row) {
      this.$router.push({
        path: '/purchase-order/consign/list/receive',
        query: {
          orderCode: row.orderCode
        }
      });
    },
    //编辑
    editGo(scope) {
      if (scope.busModel === 11) {
        this.$router.push({
          path: '/purchase-order/salesorder/add',
          query: {
            id: scope.orderId,
            detailid: scope.orderDetailId
          }
        });
      } else {
        this.$router.push({
          path: '/purchase-order/consign/add',
          query: {
            id: scope.orderId,
            detailid: scope.orderDetailId
          }
        });
      }
    },
    //查看
    checkDetail(scope) {
      if (scope.busModel === 11) {
        this.$router.push({
          path: '/purchase-order/salesorder/list/detail',
          query: {
            id: scope.orderId,
            orderCode: scope.orderCode,
            orderDetailId: scope.orderDetailId
          }
        });
      } else {
        this.$router.push({
          path: '/purchase-order/consign/list/detail',
          query: {
            id: scope.orderId,
            orderCode: scope.orderCode,
            orderDetailId: scope.orderDetailId
          }
        });
      }
    },
     //详情导出
     exportDetailEx () {
      if (this.payload.content && this.payload.content.length > 0) {
        this.detailExIsLoaded = true
        const query = {
          busModelList: [2, 4, 11],
          ...this.exportQuery,
          page: this.currentPage,
          pageSize: this.pageSize
        };
        $loadFileSimply({
            method: 'post',
            url: downloadOrderDetailInfo,
            timeout: '0',
            data: {
              ...query
            }
          }).then(res => {
            if (res.byteLength) {
              fileDownload(res, '产品详情.xlsx')
              this.detailExIsLoaded = false
            } else {
              this.detailExIsLoaded = false
              this.$message({
                message: '导出失败',
                type: 'warning'
              })
            }
          })
          .catch(err => {
            this.detailExIsLoaded = false
            this.$message({
              message: '导出失败',
              type: 'warning'
            })
          })
      } else {
        this.$message({
          message: '暂无可导出数据',
          type: 'warning'
        })
      }
    },
    // 导出
    exportEx() {
      if (this.payload.content && this.payload.content.length > 0) {
        this.isLoaded = true
        const query = {
          busModelList: [2, 4, 11],
          ...this.exportQuery,
          page: this.currentPage,
          pageSize: this.pageSize
        };
        $loadFileSimply({
            method: 'post',
            url: downloadOrderList,
            timeout: '0',
            data: {
              ...query
            }
          }).then(res => {
            if (res.byteLength) {
              fileDownload(res, '订单.xlsx')
              this.isLoaded = false
            } else {
              this.isLoaded = false
              this.$message({
                message: '导出失败',
                type: 'warning'
              })
            }
          })
          .catch(err => {
            this.isLoaded = false
            this.$message({
              message: '导出失败',
              type: 'warning'
            })
          })
      } else {
        this.$message({
          message: '暂无可导出数据',
          type: 'warning'
        })
      }
    }
  }
};
